package com.chatplus.application.scheduled;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.dao.orders.OrderDao;
import com.chatplus.application.dao.pay.PayRequestDao;
import com.chatplus.application.domain.entity.orders.OrderEntity;
import com.chatplus.application.domain.entity.pay.PayRequestEntity;
import com.chatplus.application.enumeration.AppBusinessCodeEnum;
import com.chatplus.application.enumeration.OrderStatusEnum;
import com.chatplus.application.enumeration.PayStatusEnum;
import com.chatplus.application.event.order.OrderUpdateEvent;
import com.chatplus.application.event.order.dto.OrderRequestEvent;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * 订单结果定时任务（用户补偿可能出现的回调处理错误）
 */
@Component
public class OrderTaskJob {
    private static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(OrderTaskJob.class);
    private final OrderDao orderDao;
    private final PayRequestDao payRequestDao;
    private final ApplicationContext applicationContext;

    public OrderTaskJob(OrderDao orderDao, PayRequestDao payRequestDao, ApplicationContext applicationContext) {
        this.orderDao = orderDao;
        this.payRequestDao = payRequestDao;
        this.applicationContext = applicationContext;
    }

    /**
     * 订单的支付结果定时任务,查询3小时之后的数据，之前的数据不查
     * 只针对已扫码的订单
     */
    @XxlJob(value = "OrderTaskJob#orderResultJob")
    public void orderResultJob() {
        // 获取参数
        String param = XxlJobHelper.getJobParam();
        int minute = NumberUtil.parseInt(param);
        if (minute <= 0) {
            minute = 30;
        }
        Date requestAtGt = DateUtil.offset(new Date(), DateField.MINUTE, -minute);
        LOGGER.message("开始执行定时查询支付结果").context("开始查询时间", requestAtGt).debug();
        LambdaQueryWrapper<OrderEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.ne(OrderEntity::getStatus, OrderStatusEnum.SUCCESS);
        queryWrapper.gt(OrderEntity::getCreatedAt, requestAtGt);
        List<OrderEntity> orderList = orderDao.selectList(queryWrapper);
        orderList.forEach(item -> {
            Long orderId = item.getId();
            LOGGER.message("开始查询订单支付结果").context("订单号", item.getId()).info();
            // 查询支付结果
            LambdaQueryWrapper<PayRequestEntity> payQueryWrapper = new LambdaQueryWrapper<>();
            payQueryWrapper.eq(PayRequestEntity::getBizId, orderId);
            payQueryWrapper.eq(PayRequestEntity::getBizCode, AppBusinessCodeEnum.CHAT);
            payQueryWrapper.eq(PayRequestEntity::getPayStatus, PayStatusEnum.SUCCESS);
            payQueryWrapper.orderByDesc(PayRequestEntity::getSuccessAt);
            payQueryWrapper.last("limit 1");
            PayRequestEntity payRequestEntity = payRequestDao.selectOne(payQueryWrapper);
            if (payRequestEntity != null) {
                // 订单更新成功后发送订单成功事件，并给用户添上
                OrderRequestEvent orderRequestEvent = OrderRequestEvent.builder()
                        .orderId(orderId)
                        .successAt(payRequestEntity.getSuccessAt())
                        .tradeTransactionId(payRequestEntity.getTradeTransactionId())
                        .status(OrderStatusEnum.SUCCESS)
                        .build();
                applicationContext.publishEvent(new OrderUpdateEvent(orderRequestEvent));
            }
        });
    }
}
